﻿using Exceptionless;
using Microsoft.AspNetCore.Builder;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Shared.LogHelper
{
    /// <summary>
    /// Exceptionless 
    /// 日志组件
    /// appsettings.json 增加配置
    ///   "Exceptionless": { //Exceptionless 日志使用配置信息
    ///         "ApiKey": "OvzcKg8V7bPcWU8yAYBVe6uCEKIAQm3xfEzW5yxp",
    ///         "ServerUrl": "http://localhost:50000"
    ///    }
    ///  使用参考 :https://www.cnblogs.com/savorboard/p/exceptionless.html
    /// </summary>
    public static class ExceptionlessExtensions
    {
        /// <summary>
        /// 注册 ExceptionlessClient 日志组件
        /// 在 Configure() 中进行注册
        ///     app.UseExceptionlessExt(this.Configuration);
        /// </summary>
        /// <param name="app"></param>
        /// <param name="configuration"></param>
        /// <returns></returns>
        public static IApplicationBuilder UseExceptionlessExt(this IApplicationBuilder app, IConfiguration configuration)
        {
            ExceptionlessClient.Default.Configuration.ApiKey = configuration.GetSection("Exceptionless:ApiKey").Value;

            string serverUrl = configuration.GetSection("Exceptionless:ServerUrl")?.Value;
            if (!string.IsNullOrEmpty(serverUrl))
            {
                ExceptionlessClient.Default.Configuration.ServerUrl = configuration.GetSection("Exceptionless:ServerUrl").Value;
            }

            ExceptionlessClient.Default.SubmittingEvent += OnSubmittingEvent;

            return app.UseExceptionless();
        }
        /// <summary>
        /// 绑定额外的事件，来统一自定义一些处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private static void OnSubmittingEvent(object sender, EventSubmittingEventArgs e)
        {
            // 仅处理未被处理过的异常
            if (!e.IsUnhandledError)
                return;

            // 忽略404事件
            if (e.Event.IsNotFound())
            {
                e.Cancel = true;
                return;
            }

            // 获取error对象
            var error = e.Event.GetError();
            if (error == null)
            {
                return;
            }
            //// 忽略 401 或 `HttpRequestValidationException`异常
            //if (error.Code == "401" || error.Type == "System.Web.HttpRequestValidationException")
            //{
            //    e.Cancel = true;
            //    return;
            //}

            //// 忽略不是指定命名空间代码抛出的异常
            //var handledNamespaces = new List<string> { "Exceptionless" };
            //if (!error.StackTrace.Select(s => s.DeclaringNamespace).Distinct().Any(ns => handledNamespaces.Any(ns.Contains)))
            //{
            //    e.Cancel = true;
            //    return;
            //}
        }
    }
}
